package com.bro.person.base.controller;


import com.bro.person.base.enums.error.GlobalEnum;
import com.bro.person.base.model.paging.PagingResult;
import com.bro.person.base.service.IBroBaseService;
import com.bro.person.base.utils.ResponseBuilderUtil;
import com.bro.person.base.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author swallow
 * Created by swallow on 2018/10/3.<br>
 */
public abstract class AbstractBroBaseController<T extends Serializable, TCriteria extends Serializable,ID extends Serializable> {

    private static final Logger logger = LoggerFactory.getLogger(AbstractBroBaseController.class);

    /**
     * 抽象方法
     * @return
     */
    protected abstract IBroBaseService<T,TCriteria,ID> getService();

    /**
     * 设置 该controller 对应的基本路径传输值
     */
    public Pattern p = Pattern.compile(".[a-z|A-z]+.controller.[a-z|A-z]+Controller");

    /**
     * Controller基路径
     * */
    protected String getPageBaseRoot(){
        return "";
    }


    /**
     * 功能描述：保存、修改数据字典数据
     * @param entity ddd
     * @return
     */
    @PostMapping(value = "/saveOrUpdate",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO saveOrUpdate(T entity, HttpServletRequest request, HttpServletResponse response) throws Exception{
        logger.debug("[AbstractBroBaseController][saveOrUpdate] entering entity:{},request:{},response:{}",entity, request, response);
        String id = request.getParameter("id");
        if(StringUtils.isNotBlank(id)){
            //修改信息
            int successCount = getService().updateById(entity);
            if(successCount>0){
                return ResponseBuilderUtil.buildSuccessJson(GlobalEnum.BRO_ADMIN_ADD_SUCCESS);
            }
            return ResponseBuilderUtil.buildErrorJSON(GlobalEnum.BRO_ADMIN_UPDATE_ERROR);
        }else{
            //添加信息
            int successCount = getService().save(entity);
            if(successCount>0){
                return ResponseBuilderUtil.buildSuccessJson(GlobalEnum.BRO_ADMIN_ADD_SUCCESS);
            }
            return ResponseBuilderUtil.buildErrorJSON(GlobalEnum.BRO_ADMIN_ADD_ERROR);
        }
    }

    /**
     * 功能描述：实现批量删除数据字典的记录
     * @param id
     * @return
     */
    @PostMapping(value = "/delete",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO delete(@RequestParam(value = "id",required = false,defaultValue = "-1") ID id) throws Exception{
        logger.debug("[AbstractBroBaseController][delete] entering id:{}",id);
        Map<String,Object> result = new HashMap<String, Object>();
        int deleteCont = getService().deleteById(id);
        if(deleteCont>0){
            return ResponseBuilderUtil.buildSuccessJson(GlobalEnum.BRO_ADMIN_DELETE_SUCCESS);
        }
        return ResponseBuilderUtil.buildErrorJSON(GlobalEnum.BRO_ADMIN_DELETE_EROOR);
    }


    /**
     * 功能描述：获取数据字典的分页的数据
     * @param entity
     * @return
     */
    @GetMapping(value = "/list",produces = MediaType.APPLICATION_JSON_VALUE)
    public Object list(T entity, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(value = "pageNo",required = false,defaultValue = "1") int pageNo,
                             @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize){
        String requestJson = request.getParameter("requestJson");
        PagingResult<T> tPagingResult = getService().pagingByCriteria(pageNo, pageSize, null, entity);
        //TODO 暂时写死
        if("json".equals(requestJson)){
            return ResponseBuilderUtil.buildSuccessJson(tPagingResult);
        }
        String bath;
        try {
            bath = getPageBaseRoot();
        } catch (Exception e) {
            bath = "";
        }
        RedirectView redirectView = new RedirectView(getPageBaseRoot()+"/listPaging");
        ModelAndView modelAndView = new ModelAndView(redirectView);
        modelAndView.addObject("tPagingResult",tPagingResult);
        return modelAndView;
    }

    /**
     * 通过id查询
     * @param request
     * @param response
     * @param id
     * @return
     */
    @GetMapping(value = "{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO loadObjectById(HttpServletRequest request, HttpServletResponse response,@PathVariable(value = "id") ID id){
        logger.debug("[AbstractBroBaseController][loadObjectById] entering request:{},response:{},id:{}",request, response, id);
        T t = getService().loadById(id);
        logger.info("[AbstractBroBaseController][loadObjectById] desc request:{},response:{},id:{},t:{}",request, response, id, t);
        return ResponseBuilderUtil.buildSuccessJson(t);
    }

    /**
     * 将首字母变小写
     * @param str
     * @return
     */
    private static String toFirstCharLowerCase(String str){
        char[]  columnCharArr = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < columnCharArr.length; i++) {
            char cur = columnCharArr[i];
            if(i==0){
                sb.append(Character.toLowerCase(cur));
            }else{
                sb.append(cur);
            }
        }
        return sb.toString();
    }
}
